//
//  PannelViewController.m
//  RootDirectory
//
//  Created by Ryan on 13-2-28.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "PannelViewController.h"
#import "LoginViewController.h"
#import "PatterLockViewController.h"
#import "NYMemberCenterDataManager.h"
#import "YuYueListViewController.h"

#define kLeftMenuOriginX    160.f
#define kRightMenuOriginX   -240.f

@interface PannelViewController ()

@property (nonatomic, retain) UIPanGestureRecognizer *naviPanGesture;
@property (nonatomic, retain) UISwipeGestureRecognizer *naviSwipeGesture;
@property (nonatomic, retain) UIActionSheet *phoneCallAs;
@property (nonatomic, retain) UIActionSheet *normalUserCallAs;

@end

@implementation PannelViewController

@synthesize leftMenuView,rightMenuView;
@synthesize contentNaviController;
@synthesize menuType;
@synthesize contentMaskView,contentContainView;
@synthesize naviPanGesture;
@synthesize naviSwipeGesture;
@synthesize filterView;
@synthesize phoneCallAs,normalUserCallAs;

- (FilterView *)filterView
{
    if(nil == filterView)
    {
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"FilterView" owner:self options:nil];
        filterView = [[nibs lastObject] retain];
    }
    return filterView;
}

- (LeftMenuView *)leftMenuView
{
    if(nil == leftMenuView)
    {
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"LeftMenuView" owner:self options:nil];
        leftMenuView = [[nibs lastObject] retain];
    }
    return leftMenuView;
}

- (RightMenuView *)rightMenuView
{
    if(nil == rightMenuView)
    {
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"RightMenuView" owner:self options:nil];
        rightMenuView =[[nibs lastObject] retain];
    }
    return rightMenuView;
}

- (ContentNaviController *)contentNaviController
{
    if(nil == contentNaviController)
    {
        contentNaviController = [[ContentNaviController alloc] initWithRootViewController:nil];
    }
    return contentNaviController;
}

- (UIPanGestureRecognizer *)naviPanGesture
{
    if(nil == naviPanGesture)
    {
        naviPanGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(naviViewPanWithGesture:)];
    }
    return naviPanGesture;
}

- (UISwipeGestureRecognizer *)naviSwipeGesture
{
    if(nil == naviSwipeGesture)
    {
        naviSwipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(naviViewSwipeWithGesture:)];
        naviSwipeGesture.direction = UISwipeGestureRecognizerDirectionRight;
    }
    return naviSwipeGesture;
}

- (UIActionSheet *)phoneCallAs
{
    if(nil == phoneCallAs)
    {
        phoneCallAs = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"咨询理财师",@"咨询客服", nil];
    }
    return phoneCallAs;
}

- (UIActionSheet *)normalUserCallAs
{
    if(nil == normalUserCallAs)
    {
        normalUserCallAs = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"咨询客服", nil];
    }
    return normalUserCallAs;
}


#pragma mark - Notification methods
- (void)showLeftMenuWithNotification:(NSNotification *)notification
{
    self.leftMenuView.hidden = NO;
    self.rightMenuView.hidden = YES;
    [UIView animateWithDuration:0.3f animations:^(void){
        self.contentContainView.frame = CGRectMake(kLeftMenuOriginX, self.contentContainView.frame.origin.y, self.contentContainView.frame.size.width, self.contentContainView.frame.size.height);
    } completion:^(BOOL finished){
        self.menuType = kMenuLeft;
        self.contentMaskView.hidden = NO;
    }];
}

- (void)showRightMenuViewWithNotification:(NSNotification *)notification
{
    self.leftMenuView.hidden = YES;
    self.rightMenuView.hidden = NO;
    [UIView animateWithDuration:0.3f animations:^(void){
        self.contentContainView.frame = CGRectMake(kRightMenuOriginX, self.contentContainView.frame.origin.y, self.contentContainView.frame.size.width, self.contentContainView.frame.size.height);
    } completion:^(BOOL finished){
        self.menuType = kMenuRight;
        self.contentMaskView.hidden = NO;
        //获取用户个人信息
        self.rightMenuView.isRefreshInfoForOthers = NO;
//        [self.rightMenuView callServerToGetPersonalInfo];
    }];
}

- (void)hideMenuViewWithNotification:(NSNotification *)notification
{
    [UIView animateWithDuration:0.3f animations:^(void){
        self.contentContainView.frame = self.view.bounds;
    } completion:^(BOOL finished){
        self.menuType = kMenuNone;
        self.contentMaskView.hidden = YES;
    }];
}

- (void)showLoginViewWithNotification:(NSNotification *)notification
{
    LoginViewController *lvc = [[LoginViewController alloc] init];
    UINavigationController *loginNaviController = [[UINavigationController alloc] initWithRootViewController:lvc];
    loginNaviController.navigationBar.hidden = YES;
    [self presentModalViewController:loginNaviController animated:YES];
    [lvc release];
    [loginNaviController release];
}

- (void)showPatternLockViewWithNotification:(NSNotification *)notification
{
//    kSetLockType = 0,
//    kUnlockType
    
    /**两个入口可以显示锁屏页
        1. 个人中心 - 手势密码 - 重置
        2. 左边菜单 - 手势密码 - 忘记密码 - 重置
        第一种情形: 从pannl上present pattern lock
        第二种情形: pattern lock 已经存在，只有pop to root就行
     */
    if(self.presentedViewController)
    {
        //第二种情形
        UINavigationController *nvc = (UINavigationController *)(self.presentedViewController);
        PatterLockViewController *plvc = (PatterLockViewController *)[[nvc viewControllers] objectAtIndex:0];
        plvc.lockType = kSetLockType;
        [nvc popToRootViewControllerAnimated:YES];
    }
    else
    {
        //第一种情形
        LockType lt = (LockType)[notification.object integerValue];
        PatterLockViewController *plvc = [[PatterLockViewController alloc] init];
        UINavigationController *patternLockNaviController = [[UINavigationController alloc] initWithRootViewController:plvc];
        patternLockNaviController.navigationBar.hidden = YES;
        [self presentModalViewController:patternLockNaviController animated:YES];
        plvc.lockType = lt;
        [plvc release];
        [patternLockNaviController release];
    }
}

- (void)activeNaviViewPanGestureWithNotification:(NSNotification *)notification
{
    [self.contentNaviController.view removeGestureRecognizer:self.naviSwipeGesture];
    if(![self.contentNaviController.view.gestureRecognizers containsObject:self.naviPanGesture])
        [self.contentNaviController.view addGestureRecognizer:self.naviPanGesture];
}

- (void)activeNaviViewSwipeGestureWithNotification:(NSNotification *)notification
{
    [self.contentNaviController.view removeGestureRecognizer:self.naviPanGesture];
    if(![self.contentNaviController.view.gestureRecognizers containsObject:self.naviSwipeGesture])
        [self.contentNaviController.view addGestureRecognizer:self.naviSwipeGesture];
}

- (void)showFilterViewWithNotification:(NSNotification *)notification
{
    //让pop view呈现在出header之外的最上层
    [self.view bringSubviewToFront:self.filterView];
    
    NSDictionary *dict = notification.userInfo;
    NSArray *filerProperties = [dict objectForKey:kFilterPropertiesKey];
    self.filterView.filterProperties = filerProperties;
    self.filterView.locationType = (FilterLocationType)[[dict objectForKey:kFilterLocationType] integerValue];
    self.filterView.type = (FitlerType)[[dict objectForKey:kFilterTypeKey] integerValue];
    CGRect rect = self.filterView.filterTableView.frame;
    rect.size.height = self.filterView.filterTableView.rowHeight*filerProperties.count;
    self.filterView.filterTableView.frame = rect;
    
    [self.filterView reloadData];
    
    [self.filterView addAnimationWithType:kCATransitionFade subtype:nil];
    self.filterView.hidden = NO;
}

- (void)hideFilterViewWithNotification:(NSNotification *)notification
{
    [self.filterView addAnimationWithType:kCATransitionFade subtype:nil];
    self.filterView.hidden = YES;
}

- (void)showPhoneCallWithNotification:(NSNotification *)notification
{
    if([NYMemberCenterDataManager sharedManager].loginMember.memberType == kMemberAuthentication)
        [self.phoneCallAs showInView:self.view];
    else
    {
        [self.normalUserCallAs showInView:self.view];
    }
}

#pragma mark - Gesture methods
- (void)naviViewPanWithGesture:(UIPanGestureRecognizer *)gesture
{
    CGRect rectForNaviView = self.contentContainView.frame;
    
    CGPoint translationPoint = [gesture translationInView:self.view];
    CGFloat moveX = translationPoint.x;
    CGFloat naviX = rectForNaviView.origin.x;
    
    if(naviX >=0)
    {
        self.leftMenuView.hidden = NO;
        self.rightMenuView.hidden = YES;
    }
    else
    {
        self.leftMenuView.hidden = YES;
        self.rightMenuView.hidden = NO;
    }
    
    CGPoint currentVelocityPoint = [gesture velocityInView:self.view];
    CGFloat currentVelocityX     = currentVelocityPoint.x;
    
    if(gesture.state == UIGestureRecognizerStateEnded || gesture.state == UIGestureRecognizerStateCancelled)
    {
        //手势结束后菜单全部显示或隐藏
        if(naviX < 0)
        {
            //显示右菜单
            if(currentVelocityX > 0)
                [self hideMenuViewWithNotification:nil];
            else
                [self showRightMenuViewWithNotification:nil];
        }
        else
        {
            //显示左菜单
            if(currentVelocityX > 0)
                [self showLeftMenuWithNotification:nil];
            else
                [self hideMenuViewWithNotification:nil];
        }
    }
    else
    {
        //手势移动过程中的contentview 管理
        if(self.menuType == kMenuNone)
        {
            naviX = 0+moveX;
        }
        else if(self.menuType == kMenuLeft)
        {
            naviX = kLeftMenuOriginX+moveX;
        }
        else
        {
            naviX = kRightMenuOriginX+moveX;
        }
        if(naviX > kLeftMenuOriginX)
            naviX = kLeftMenuOriginX;
        if(naviX < kRightMenuOriginX)
            naviX = kRightMenuOriginX;
        
        //如果用户没有登录，则无法显示右菜单
        if(![[NYMemberCenterDataManager sharedManager] isLogin])
        {
            if(naviX < 0)
                naviX = 0;
        }
        
        rectForNaviView.origin.x = naviX;
        self.contentContainView.frame = rectForNaviView;
    }
}

- (void)maskViewTapWithGesture:(UITapGestureRecognizer *)gesture
{
    [self hideMenuViewWithNotification:nil];
}

- (void)naviViewSwipeWithGesture:(UISwipeGestureRecognizer *)gesture
{
    id vc = [self.contentNaviController topViewController];
    if([vc isKindOfClass:[YuYueListViewController class]])
    {
        YuYueListViewController *yylvc = (YuYueListViewController *)vc;
        if(!yylvc.isFromRightMenu && yylvc.isFromEdit)
        {
            [self.contentNaviController popToViewController:[[self.contentNaviController viewControllers] objectAtIndex:1] animated:YES];
            return;
        }
    }
    
    [self.contentNaviController popViewControllerAnimated:YES];
}

#pragma mark - UIViewController methods

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showLeftMenuWithNotification:) name:kShowLeftMenuNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showRightMenuViewWithNotification:) name:kShowRightMenuNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideMenuViewWithNotification:) name:kHideMenuNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showLoginViewWithNotification:) name:kShowLoginViewNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showPatternLockViewWithNotification:) name:kShowPatternLockViewNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(activeNaviViewPanGestureWithNotification:) name:kActiveNaviPanGestureNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(activeNaviViewSwipeGestureWithNotification:) name:kActiveNaviSwipeGestureNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showFilterViewWithNotification:) name:kShowFilterViewNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideFilterViewWithNotification:) name:kHideFilterViewNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showPhoneCallWithNotification:) name:kShowPhoneCallNotification object:nil];
    //添加filterview-默认隐藏
    [self.view addSubview:self.filterView];
    self.filterView.hidden = YES;
    self.filterView.frame = self.view.bounds;

    //添加左/右菜单
    [self.view addSubview:self.leftMenuView];
    [self.view addSubview:self.rightMenuView];
    //添加内容navi contain view
    
    [self.contentContainView addSubview:self.contentNaviController.view];
    self.contentNaviController.view.frame = self.contentContainView.bounds;
    self.contentNaviController.view.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    
    //添加手势
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(maskViewTapWithGesture:)];
    [self.contentMaskView addGestureRecognizer:tapGesture];
    [tapGesture release];
    
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(naviViewPanWithGesture:)];
    [self.contentMaskView addGestureRecognizer:panGesture];
    [panGesture release];
    
    [self.view bringSubviewToFront:self.contentContainView];
    [self.contentContainView bringSubviewToFront:self.contentMaskView];
    //默认菜单选择为kMenuNone
    self.menuType = kMenuNone;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.isViewLoaded && !self.view.window)
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        self.view = nil;
        self.leftMenuView = nil;
        self.rightMenuView = nil;
        self.contentNaviController = nil;
        self.contentMaskView = nil;
        self.contentContainView = nil;
        self.filterView = nil;
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.leftMenuView = nil;
    self.rightMenuView = nil;
    self.contentNaviController = nil;
    self.contentMaskView = nil;
    self.contentContainView = nil;
    self.filterView = nil;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [normalUserCallAs release];
    [phoneCallAs release];
    [filterView release];
    [naviSwipeGesture release];
    [naviPanGesture release];
    [contentContainView release];
    [contentMaskView release];
    [leftMenuView release];
    [rightMenuView release];
    [contentNaviController release];
    [super dealloc];
}

#pragma mark - UIActionSheetDelegate methods
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(actionSheet == phoneCallAs)
    {
        if(buttonIndex == 0)
        {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",[NYMemberCenterDataManager sharedManager].loginMember.fp_mobile]]];
        }
        else if(buttonIndex == 1)
        {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",[NYMemberCenterDataManager sharedManager].loginMember.custom_service_phone]]];
        }
    }
    else
    {
        if(buttonIndex == 0)
        {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",[NYMemberCenterDataManager sharedManager].loginMember.custom_service_phone]]];
        }
    }
}
@end
